/*
 * Copyright (c) 2014 Hai Bison
 *
 * See the file LICENSE at the root directory of this project for copying
 * permission.
 */

package haibison.simpleprovider.services;

import static haibison.simpleprovider.BuildConfig.DEBUG;
import android.Manifest.permission;
import android.app.IntentService;
import android.content.pm.PackageManager;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

/**
 * Base intent service. This uses {@link WakeLock} for its entire lifetime. So
 * to make sure this service works properly, please add permission
 * {@link permission#WAKE_LOCK} to your {@code AndroidManifest.xml}.
 * 
 * @author Hai Bison
 * 
 */
public abstract class BaseIntentService extends IntentService {

    private static final String CLASSNAME = BaseIntentService.class.getName();

    private WakeLock mWakeLock;
    private boolean mDestroyed = false;

    /**
     * Creates new instance.
     */
    public BaseIntentService() {
        super(CLASSNAME + "::" + System.currentTimeMillis());
    }// BaseIntentService()

    @Override
    public void onCreate() {
        super.onCreate();

        if (DEBUG)
            Log.d(CLASSNAME, "onCreate()");

        mDestroyed = false;

        /*
         * Setup wake lock.
         */
        if (checkCallingOrSelfPermission(permission.WAKE_LOCK) == PackageManager.PERMISSION_GRANTED) {
            mWakeLock = ((PowerManager) getSystemService(POWER_SERVICE))
                    .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, CLASSNAME);
            mWakeLock.acquire();
        }// if
    }// onCreate()

    @Override
    public void onDestroy() {
        if (DEBUG)
            Log.d(CLASSNAME, "onDestroy()");

        try {
            if (mWakeLock != null && mWakeLock.isHeld())
                mWakeLock.release();
        } catch (Throwable t) {
            Log.e(CLASSNAME, t.getMessage(), t);
        }

        mDestroyed = true;

        super.onDestroy();
    }// onDestroy()

    /**
     * Checks to see if the service is destroyed.
     * 
     * @return {@code true} or {@code false}.
     */
    protected boolean isDestroyed() {
        return mDestroyed;
    }// isDestroyed()

}
